from rest_framework import serializers
from users.models import User
from submission.models.submission_model import SubmissionModel

class UserProfileSerializer(serializers.ModelSerializer):
    solved_problems = serializers.SerializerMethodField()
    total_submissions = serializers.SerializerMethodField()
    accepted_submissions = serializers.SerializerMethodField()
    created_time = serializers.DateTimeField(source='date_joined', read_only=True)
    last_login = serializers.DateTimeField(read_only=True)

    class Meta:
        model = User
        fields = [
            'id', 'username', 'email', 'nick_name', 'avatar',
            'created_time', 'last_login', 'points', 'level',
            'solved_problems', 'total_submissions', 'accepted_submissions', 'is_staff'
        ]
        read_only_fields = ['id', 'created_time', 'last_login', 'is_staff']

    def get_solved_problems(self, obj):
        # 获取用户解决的不同题目数量
        return SubmissionModel.objects.filter(
            user=obj,
            result=3
        ).values('problem').distinct().count()

    def get_total_submissions(self, obj):
        # 获取用户的总提交次数
        return SubmissionModel.objects.filter(user=obj).count()

    def get_accepted_submissions(self, obj):
        # 获取用户通过的提交次数
        return SubmissionModel.objects.filter(
            user=obj,
            result=3
        ).count()

class UserUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['email', 'nick_name', 'avatar']
        extra_kwargs = {
            'email': {'required': False},
            'nick_name': {'required': False},
            'avatar': {'required': False}
        }
